package servlets.user;

import hibernate.method.UserMethods;
import hibernate.model.User;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import external.EmailUtility;
import external.TokenGenerator;

/**
 * Servlet implementation class Edit
 */
@MultipartConfig(maxFileSize = 16177215)
@WebServlet(name = "EditUser", urlPatterns = { "/EditUser" })
public class Edit extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String host;
	private String port;
	private String user;
	private String pass;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Edit() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() {
		// reads SMTP server setting from web.xml file
		ServletContext context = getServletContext();
		host = context.getInitParameter("host");
		port = context.getInitParameter("port");
		user = context.getInitParameter("user");
		pass = context.getInitParameter("pass");
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		response.setContentType("text/html");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session s = sessionFactory.openSession();
		HttpSession session = request.getSession();
		s.beginTransaction();
		UserMethods user_m = new UserMethods();
		User u = user_m.id_to_user(sessionFactory, s, (Integer) session.getAttribute("user_id"));
		//String userek = (String) request.getParameter("user_id");
		//User u = user_m.id_to_user(sessionFactory, s, Integer.parseInt(userek));
		String password = (String) request.getParameter("password");
		String birthdate = (String) request.getParameter("birth_date");
		String email = (String) request.getParameter("email");
		String gender = (String) request.getParameter("gender");
		//String type = (String) request.getParameter("type");
		String name = (String) request.getParameter("name");
		String surname = (String) request.getParameter("surname"); 
		String phone = (String) request.getParameter("phone");
		InputStream inputStream = null;	// input stream of the upload file
		try {
			String dbURL = "jdbc:mysql://localhost:3306/thesis";
			String dbUser = "root";
			String dbPass = "";

			Connection conn = null;	
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
			
			
		
		Part filePart = request.getPart("avatar");
		if (filePart != null) {
			// prints out some information for debugging
			System.out.println(filePart.getName());
			System.out.println(filePart.getSize());
			System.out.println(filePart.getContentType());
			
			// obtains input stream of the upload file
			inputStream = filePart.getInputStream();
		}
		
		
		response.setContentType("text/html");
		if (inputStream  !=null && filePart.getSize()>0){
			String sql1 = "DELETE FROM usersavatars WHERE user_id = ?";
			PreparedStatement stat1 = conn.prepareStatement(sql1);
			stat1.setLong(1,  u.getUser_id());
			stat1.execute();
			
			String sql = "INSERT INTO usersavatars (user_id, avatar) values (?, ?)";
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setLong(1, u.getUser_id());
			statement.setBlob(2, inputStream);
			statement.executeUpdate();
		}
		
		if(gender != null && (!u.getGender().equals(gender))){
			user_m.edit_gender(sessionFactory, s, gender, u);
		}
		
		if(password.length()>0){
			user_m.edit_password(sessionFactory, s, password, u);
		}
		
		if(birthdate !=null && (!u.getBirthdate().equals(birthdate))){
			user_m.edit_birthdate(sessionFactory, s, birthdate, u);
		}
		
		if(email !=null && (!u.getEmail().equals(email))){
			String token = TokenGenerator.generateToken();
			user_m.insertToken(sessionFactory, s, token, "changeEmail", u.getUser_id(), email);
			String tresc = EmailUtility.sendChangeEmail(TokenGenerator.linkWithToken(token, "changeEmail", u.getUser_id()), u.getUsername());
			EmailUtility.sendEmail(host, port, user, pass, email, "[HexGames Social] Zmiana adresu email", tresc);
			
		}
		
		if (name.trim().length()>0 && (!u.getName().equals(name.trim()))){
			user_m.edit_name(sessionFactory, s, name.trim(), u);
		}
		
		if(surname.trim().length()>0 && (!u.getSurname().equals(surname.trim()))){
			user_m.edit_surname(sessionFactory, s, surname.trim(), u);
		}
		
		if(phone.trim().length()>0&& (!u.getPhone().equals(phone.trim()))){
			user_m.edit_phone(sessionFactory, s, phone.trim(), u);
		}
		
		
		
		
		s.getTransaction().commit();
		s.flush();
		s.clear();
		out.println("<script type=\"text/javascript\">alert(\"Dokonano zmian w twoim profilu\"); window.location.href = \"social/index.jsp?page=main\";</script>");
		
		}
		catch (Exception e){ 
			System.err.println(e.getMessage());
			out.println("<script type=\"text/javascript\">alert(\"Nie udalo sie dokonac zmian. Za utrudnienia przepraszamy\"); window.location.href = \"social/index.jsp?page=main\";</script>");
		}
		s.close();
	}
}